mod api;
mod config;
mod download;
mod error;
mod tui;

use std::{fs::File, io};

use ratatui::{prelude::CrosstermBackend, Terminal};
use simplelog::{CombinedLogger, ConfigBuilder, WriteLogger};

use crate::tui::{
    app::App,
    event::EventHandler,
    handler::{handle_key_events, handle_mouse_events},
    Tui,
};

type Result<T> = anyhow::Result<T>;

#[tokio::main]
async fn main() -> Result<()> {
    CombinedLogger::init(vec![WriteLogger::new(
        log::LevelFilter::Debug,
        ConfigBuilder::new().build(),
        File::create("sd-model-helper.log").unwrap(),
    )])?;
    let cfg_str = std::fs::read_to_string("sd-model-helper/sd_config.toml")?;
    let cfg = toml::from_str::<config::SDConfig>(cfg_str.as_str())?;
    let mut app = App::new(cfg);
    let backend = CrosstermBackend::new(io::stderr());
    let terminal = Terminal::new(backend)?;
    let events = EventHandler::new(250);
    let mut t = Tui::new(terminal, events);
    t.init()?;
    while app.running {
        t.draw(&mut app)?;
        match t.events.next()? {
            tui::event::Event::Tick => app.tick(),
            tui::event::Event::Key(key_event) => handle_key_events(key_event, &mut app).await?,
            tui::event::Event::Mouse(mouse_event) => {
                handle_mouse_events(mouse_event, &mut app).await?
            }
            tui::event::Event::Resize(_, _) => {}
        }
    }
    t.exit()?;
    Ok(())
}
